package com.inter.controller.unused;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.DeviceFlowUsage;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.entity.newinterentity.devicetrafficusage.request.RequestQueryDeviceTrafficUsage;
import com.inter.entity.newinterentity.devicetrafficusage.request.RequestQueryDeviceTrafficUsageData;
import com.inter.entity.newinterentity.devicetrafficusage.request.RequestQueryDeviceTrafficUsageTradeData;
import com.inter.entity.newinterentity.devicetrafficusage.response.ResponseQueryDeviceTrafficUsage;
import com.inter.entity.newinterentity.devicetrafficusage.response.ResponseQueryDeviceTrafficUsageData;
import com.inter.entity.newinterentity.devicetrafficusage.response.ResponseQueryDeviceTrafficUsageTradeData;
import com.inter.entity.newpojo.Constant;
import com.inter.insideinterservice.newservice.TurnToQueryDeviceFlowUsageService;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Api(description = "查询指定的设备指定的月份的流量使用情况")
public class QuerySpecifiedDeviceAndMonthController {

    private static Logger logger = Logger.getLogger(QuerySpecifiedDeviceAndMonthController.class);

    @Autowired
    private SequenceService sequenceService;
    @Autowired
    PartnerService partnerService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;

    @CrossOrigin
    @RequestMapping(value = "queryDeviceAndMonth", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询指定的设备流量使用情况", response = ResponseQueryDeviceTrafficUsage.class)
    public String queryDeviceAndMonth(@ApiParam @RequestBody RequestQueryDeviceTrafficUsage requestQueryDeviceTrafficUsage) {

        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestQueryDeviceTrafficUsage);
        if (requestStr == null) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求是：" + requestStr);
            RequestQueryDeviceTrafficUsage requestPackage = JSONArray.parseObject(requestStr, RequestQueryDeviceTrafficUsage.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestQueryDeviceTrafficUsageData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String partnerName = partnerProductPackageService.queryPartnerNameBypartnerCode(partnerCode);
                    String secret = partnerService.findSecretByPartnerCode(partnerCode);
                    logger.info("渠道名称：" + partnerName + ";密钥是：" + secret);
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();

                    RequestQueryDeviceTrafficUsageTradeData tradeData = requestData.getTradeData();

                    if (partnerCode == null || partnerCode == "" || ConnSeqNo == null || ConnSeqNo == "" || tradeTime == null || tradeTime == "" || token == null || token == "" || tradeType == null || tradeType == "" || lang == null || lang == "" || tradeData == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        String deviceId = requestData.getTradeData().getDeviceId();
                        String month = requestData.getTradeData().getMonth();

                        if (deviceId == null || deviceId == "" || month == null || month == "") {
                            logger.info("请求报文不合法:tradeData的值为null或者为空");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            String sign = utils.calculateSignature(str);
                            logger.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                logger.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                //签名通过，去北京接口查询
                                TurnToQueryDeviceFlowUsageService deviceFlowUsage = new TurnToQueryDeviceFlowUsageService();
                                DeviceFlowUsage flowUsage = deviceFlowUsage.querySpecifiedDeviceAndMonth(deviceId, month, partnerCode, secret);
                                if (flowUsage == null) {
                                    ResponseQueryDeviceTrafficUsageData data = new ResponseQueryDeviceTrafficUsageData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(curtime);
                                    data.setTradeRstCode(1201);
                                    data.setTradeRstMessage("The current device traffic usage was not queried;未查询到当前设备的流量使用情况!");

                                    ResponseQueryDeviceTrafficUsage deviceRealTime = new ResponseQueryDeviceTrafficUsage();
                                    deviceRealTime.setData(data);
                                    deviceRealTime.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                    // 返回给调用者的报文
                                    jsonString = JSON.toJSONString(deviceRealTime);
                                    logger.info("响应报文：" + jsonString);
                                    return jsonString;

                                } else {

                                    if (true == Constant.RET_CODE_0000.equalsIgnoreCase(flowUsage.getRetCode())) {

                                        List<ResponseQueryDeviceTrafficUsageTradeData> usageTradeDatatradeData = new ArrayList<ResponseQueryDeviceTrafficUsageTradeData>();
                                        ResponseQueryDeviceTrafficUsageTradeData tra = new ResponseQueryDeviceTrafficUsageTradeData();
                                        tra.setFlow(flowUsage.getFlow());
                                        usageTradeDatatradeData.add(tra);

                                        ResponseQueryDeviceTrafficUsageData data = new ResponseQueryDeviceTrafficUsageData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(curtime);
                                        data.setTradeRstCode(1000);
                                        data.setTradeRstMessage("success");
                                        data.setTradeData(usageTradeDatatradeData);

                                        ResponseQueryDeviceTrafficUsage deviceRealTime = new ResponseQueryDeviceTrafficUsage();
                                        deviceRealTime.setData(data);
                                        deviceRealTime.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(deviceRealTime);
                                        logger.info("响应报文：" + jsonString);
                                        return jsonString;

                                    } else {
                                        ResponseQueryDeviceTrafficUsageData data = new ResponseQueryDeviceTrafficUsageData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(curtime);
                                        data.setTradeRstCode(Integer.parseInt(flowUsage.getRetCode()));
                                        data.setTradeRstMessage(flowUsage.getResultInfo());

                                        ResponseQueryDeviceTrafficUsage deviceRealTime = new ResponseQueryDeviceTrafficUsage();
                                        deviceRealTime.setData(data);
                                        deviceRealTime.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(deviceRealTime);
                                        logger.info("响应报文：" + jsonString);
                                        return jsonString;

                                    }

                                }


                            }
                        }
                    }
                }
            }
        }
    }
}
